package io.zhengsh.order.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
// import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.freemarker.SpringTemplateLoader;

import java.util.Locale;
import java.util.Map;
import java.util.Optional;

/**
 * @descriptions: 一个模板工具
 * @author: xucl
 * @date: 2020/07/01 20:05
 * @version: 1.0
 */
@Slf4j
public class FreeMarkerUtils {

    static Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    static {
        cfg.setEncoding(Locale.CHINA, "utf-8");
        cfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(),"templates1/"));
    }

    /**
     * 获取模板
     *
     * @param templateName
     * @return
     */
    public static Template getTpl(String templateName){
        try {
            Template template = cfg.getTemplate(templateName);
            return template;
        } catch (Exception e) {
            log.error("获取模板失败 {}",templateName,e);
            return null;
        }
    }

    /**
     * 获取模板写入后的内容
     *
     * @param templateName
     * @param model
     * @return
     */
    public static Optional<String> getTplText(String templateName, Map<String, Object> model){
        try {
            Template template = cfg.getTemplate(templateName);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            return Optional.ofNullable(text);
        } catch (Exception e) {
            log.error("获取模板内容失败 {}",templateName,e);
            return Optional.empty();
        }
    }
}
